package com.example.customer01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.customer01.mapper.StudentMapper;
import com.example.customer01.pojo.Student;
import com.example.customer01.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 学生服务实现类
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    @Transactional
    public Student createStudent(Student student) {
        // 檢查學號是否已存在
        Student existingStudent = getStudentByNumber(student.getStudentNumber());
        if (existingStudent != null) {
            throw new RuntimeException("學號已存在");
        }
        
        student.setStatus("ACTIVE");
        student.setDeleted(0);
        save(student);
        return student;
    }

    @Override
    @Transactional
    public boolean deleteStudent(Integer id) {
        return removeById(id);
    }

    @Override
    @Transactional
    public Student updateStudent(Student student) {
        updateById(student);
        return student;
    }

    @Override
    public Student getStudentById(Integer id) {
        return getById(id);
    }

    @Override
    public List<Student> getAllStudents() {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getDeleted, 0);
        return list(wrapper);
    }

    @Override
    public Student getStudentByNumber(String studentNumber) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentNumber, studentNumber)
               .eq(Student::getDeleted, 0);
        return getOne(wrapper);
    }

    @Override
    public Student getStudentWithCourses(Integer studentId) {
        return studentMapper.findStudentWithCourses(studentId);
    }

    @Override
    public IPage<Student> getStudentPage(Page<Student> page, String keyword) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Student::getName, keyword)
                    .or()
                    .like(Student::getStudentNumber, keyword)
                    .or()
                    .like(Student::getEmail, keyword);
        }

        queryWrapper.eq(Student::getDeleted, 0)
                .orderByDesc(Student::getCreateTime);

        return studentMapper.selectPage(page, queryWrapper);
    }
} 